package chapter29;

import java.applet.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import chapter15.StillClock;

public class ClockWithAudio extends JApplet{
	
	protected AudioClip[] hourAudio = new AudioClip[12];
	protected AudioClip[] minuteAudio = new AudioClip[60];
	
	protected AudioClip amAudio = 
			Applet.newAudioClip(this.getClass().getResource("audio/am.au"));
	protected AudioClip pmAudio = 
			Applet.newAudioClip(this.getClass().getResource("audio/pm.au"));
	
	private StillClock clock = new StillClock();
	
	private Timer timer = new Timer(1000, new TimerListener());
	
	private JLabel jlbDigitTime = new JLabel("", JLabel.CENTER);
	
	public void init() {
		for (int i = 0; i < 12; i++) {
			hourAudio[i] = Applet.newAudioClip(this.getClass().getResource("audio/hour" + i + ".au"));
		}
		
		for (int i = 0; i < 60; i++) {
			minuteAudio[i] = Applet.newAudioClip(this.getClass().getResource("audio/minute" + i + ".au"));
		}
		
		add(clock, BorderLayout.CENTER);
		add(jlbDigitTime, BorderLayout.SOUTH);
	}
	
	public void start(){
		timer.start();
	}
	
	public void stop(){
		timer.stop();
	}
	
	private class TimerListener implements ActionListener{
		public void actionPerformed(ActionEvent e){
			clock.setCurrentTime();
			clock.repaint();
			jlbDigitTime.setText(clock.getHour() + ":" + clock.getMinute() + ":" + clock.getSecond());
			if (clock.getSecond() == 0) {
				announceTime(clock.getHour(), clock.getMinute());
			}
		}
	}
	
	public void announceTime(int hour, int minute){
		//在同一个线程中播报音频时，为保证这些音频剪辑不会相互冲突，而在播报小时和分钟后设置了延时，这会导致每分钟的前3秒不会更新
		hourAudio[hour % 12].play();
		
		try{
			Thread.sleep(1500);
			
			minuteAudio[minute].play();
			
			Thread.sleep(1500);
		}
		catch (InterruptedException ex) {
		}
		
		if (hour < 12)
			amAudio.play();
		else
			pmAudio.play();
	}
	
	public void announceTimeWithSeparateThread(int hour, int minute){
		//在独立的线程上报时
		new Thread(new AnnounceTimeOnSeparateThread(hour, minute)).start();
	}
	
	class AnnounceTimeOnSeparateThread implements Runnable{
		private int hour, minute;
		
		public AnnounceTimeOnSeparateThread(int hour, int minute){
			this.hour = hour;
			this.minute = minute;
		}
		
		public void run(){
			announceTime(hour, minute);
		}
	}

}
